package com.yundingai.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yundingai.ai.cache.RedisChatMemory;
import com.yundingai.domain.vo.ChatVO;
import com.yundingai.service.ChatService;
import com.yundingai.vm.constant.RedisConstant;
import com.yundingai.vm.enums.AiSystemPromptEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import org.springframework.ai.chat.client.ChatClient;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
  * @Author: liyuxiang
  * @Date: 2025/7/17 13:58
  */

@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    @Autowired
    ChatClient chatClient;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisChatMemory chatMemory;



    @Override
    public Flux<ChatResponse> chatStream(ChatVO chatVO) {
        // 创建搜索请求，用于搜索相关文档
        SearchRequest searchRequest = SearchRequest.builder()
                                           .query(chatVO.getQuestion()) // 设置查询条件
                                           .topK(3) // 设置最多返回的文档数量
                                           .build();


        // 调用聊天客户端生成流式响应内容
        return this.chatClient.prompt()
                              .system(prompt -> prompt
                                      .param("prompt", AiSystemPromptEnum.getByCode(Integer.parseInt(chatVO.getPromptId())).getPrompt())
                                      .param("now", DateUtil.now()) // 设置系统角色参数
                                      .param("userId", chatVO.getSessionId())) // 添加用户ID参数
                              // 设置会话记忆参数
                              .advisors(advisor -> advisor
//                                      .advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest)) // 设置RAG的Advisor
                                      .param("stream", true)
                                      .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatVO.getSessionId()))
                              .user(chatVO.getQuestion())
                              .stream()
                .chatResponse();
    }

    @Override
    public Flux<ChatResponse> streamMessage(ChatVO chatVO) {


        return Flux.create(sink -> {
            try {

                // 使用Spring AI的流式API
                Flux<ChatResponse> contentStream = chatClient.prompt()
                                                             .system(prompt -> prompt.param("now", DateUtil.now()))
                                                             .advisors(advisor->advisor.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,chatVO.getSessionId()))
                                                             .user(chatVO.getQuestion())
                                                             .stream()
                                                             .chatResponse();
//                                                       .content();

                // 订阅流式内容并转发给前端
//                contentStream
//                        .doOnNext(content -> {
//                            log.debug("📨 流式内容片段: {}", content);
//                            // 发送SSE格式的数据
//                            sink.next("data: " + content + "\n\n");
//                        })
//                        .doOnComplete(() -> {
//                            log.info("✅ 流式对话完成");
//                            sink.next("data: [DONE]\n\n");
//                            sink.complete();
//                        })
//                        .doOnError(error -> {
//                            log.error("❌ 流式对话错误: {}", error.getMessage());
//                            sink.error(error);
//                        })
//                        .subscribe();

            } catch (Exception e) {
                log.error("❌ 流式对话启动失败: {}", e.getMessage());
                sink.error(e);
            }
        });
    }

    @Override
    public List<Message> getChatMessages(String sessionId) {
        List<Message> messageList = chatMemory.get(sessionId, -1);
        return messageList.stream()
                          .sorted((a, b) -> -1)
                          .collect(Collectors.toList());
    }

    @Override
    public void removeChatMessages(String sessionId) {
        chatMemory.clear(sessionId);
    }

    @Override
    public Flux<String> testStream(String question, String sessionId) {
        return this.chatClient.prompt()
                              .system(prompt -> prompt.param("now", DateUtil.now())) // 设置系统角色参数
                              // 设置会话记忆参数
                              .advisors(advisor -> advisor
//                                      .advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest)) // 设置RAG的Advisor
                                .param("stream", true)
                                .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId))
                              .user(question)
                              .stream()
                .content();
    }

    @Override
    public void removeByMessageId(String sessionId, String messageId) {
        chatMemory.delete(sessionId, messageId);
    }

}
